import { ReactNode, useState } from "react";
import Taro, { getCurrentPages } from "@tarojs/taro";

import { View } from "@tarojs/components";
import ByIcon from "../ui/ByIcon";

import { useMount } from "ahooks";
import { omit } from "lodash-es";

type PageHeaderProps = {
  title?: string;

  // 重启动目标页面
  launchUrl?: string;

  // 展示返回按钮
  showBack?: boolean;

  children?: ReactNode;

  slotRight?: ReactNode;

  className?: string

  onBack?: () => void;
};

export default ({
  title,
  showBack = true,
  launchUrl,
  className,

  children,
  slotRight,

  onBack,
}: PageHeaderProps) => {
  const [style, setStyle] = useState<{
    height?: string;
    paddingTop?: string;
    paddingRight?: string;
  }>({});

  useMount(() => {
    // 胶囊几何信息
    const { top, left, height } = Taro.getMenuButtonBoundingClientRect();
    const { windowWidth } = Taro.getWindowInfo();

    setStyle({
      height: height + "px",
      paddingTop: top + "px",
      paddingRight: windowWidth - left + "px",
    });
  });

  const handleBack = () => {
    if (onBack) {
      return onBack();
    }

    const flag = getCurrentPages().length == 1;
    if (flag) {
      Taro.reLaunch({ url: launchUrl || "/pages/index/index" });
    } else {
      Taro.navigateBack({ delta: 1 });
    }
  };

  return (
    <View className={`pb-2 ${className}`} style={omit(style, "height")}>
      <View className="flex items-center px-3">
        {showBack && (
          <View
            className="flex-center w-[46px] h-[46px] mr-3"
            onClick={handleBack}
          >
            <ByIcon name="ArrowLeft" size={36} />
          </View>
        )}

        <View
          className="relative flex flex-auto items-center min-h-[70px]"
          style={{ minHeight: style.height }}
        >
          {children ?? <text className="text-lg">{title}</text>}
        </View>

        {slotRight}
      </View>
    </View>
  );
};
